export const apiIp = 'http://b2cbgapi-demo.shhvip.com'

/**
 * 数据变为SelectOptions形式[{label:‘名称’, value:1}]
 * @param data
 * @returns {*[]}
 */
export function toSelectOptions(data) {
  const options = []
  for (const key in data) {
    options.push({ label: key, value: data[key] })
  }
  return options
}

/**
 * 从SelectOptions中获取label
 * @param data
 * @returns {*[]}
 */
export function getLabelByValue(selectOptions, value, labelName, valueName) {
  let label
  if (labelName === undefined) {
    labelName = 'label'
  }
  if (valueName === undefined) {
    valueName = 'value'
  }
  for (let i = 0; i < selectOptions.length; ++i) {
    if (selectOptions[i][valueName] === value) {
      label = selectOptions[i][labelName]
    }
  }
  return label
}

/**
 * 制作RequestJson，主要解决跨域需要固定加的东西
 * @param method
 * @param url
 * @param params
 * @param responseType
 * @returns {{mode: string, headers: {"Content-Type": string}, method, params, url: string}}
 */
export function makeRequestJson(method, url, params, responseType, headers) {
  // console.log(params)
  return {
    url: apiIp + url,
    method: method,
    mode: 'cors',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded' + headers
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    responseType: responseType,
    params: method === 'get' ? params : undefined,
    data: method === 'post' ? params : undefined
  }
}

/**
 * csv导出
 * @param content   文件流
 */
export function csvExport(content) {
  // 组装a标签
  const elink = document.createElement('a')
  // 设置下载文件名
  elink.download = '附件.csv'
  elink.style.display = 'none'
  const blob = new Blob([content], { type: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel' })
  elink.href = URL.createObjectURL(blob)
  document.body.appendChild(elink)
  elink.click()
  document.body.removeChild(elink)
}

export function confirm(thisObj, title, yesCallback, noCallback) {
  return new Promise((res, rej) => {
    thisObj.$confirm(title, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      yesCallback && yesCallback()
      thisObj.$message({
        type: 'success',
        message: '删除成功!'
      })
      return res()
    }).catch(() => {
      noCallback && noCallback()
      thisObj.$message({
        type: 'info',
        message: '已取消'
      })
      return rej()
    })
  })
}
